package com.bw.module_live.fans

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.lib_common.base.BaseMVIActivity
import com.bw.lib_common.utils.setSingClick
import com.bw.lib_common.websocket.WebSocketUtils
import com.bw.lib_storage.UserMMKV
import com.bw.module_live.R
import com.bw.module_live.databinding.ActivityLive2Binding
import com.bw.module_live.fans.intent.LiveFansIntent
import com.bw.module_live.fans.model.entity.GiftEntity
import com.bw.module_live.fans.model.entity.SendGiftRequestEntity
import com.bw.module_live.fans.state.AddHotLiveRoomState
import com.bw.module_live.fans.state.EnterRoomState
import com.bw.module_live.fans.state.ExitRoomState
import com.bw.module_live.fans.state.GoodsListState
import com.bw.module_live.fans.state.JoinRedPacketState
import com.bw.module_live.fans.state.SendGiftState
import com.bw.module_live.fans.viewmodel.LiveViewModel
import com.bw.module_live.im.LiveIM
import com.bw.module_live.im.MessageListener
import com.bw.module_live.widget.BezierView
import com.google.gson.Gson
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.live2.V2TXLivePlayer
import com.tencent.live2.impl.V2TXLivePlayerImpl
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.java_websocket.handshake.ServerHandshake
import org.json.JSONObject
import java.net.URL

/**
 * 观众：
 * 1.拉流播放
 * 2.加入直播间
 * 3.实时接受消息：websocket
 * 链接成功{"type":0,"data":"连接成功"}
 * 接受到红包：{"type":1,"data":{"id":565,"room_id":"10456123","count":1,"money":10.0,"time":60000,"createTime":"Oct 27, 2025, 4:06:16 PM","status":1}}
 * 有人加入{"type":5,"data":{"id":9266,"username":"ytx22","password":"","ctime":"Oct 27, 2025, 3:37:40 PM"}}
 */
@AndroidEntryPoint
class LiveActivity : BaseMVIActivity() {
    companion object{
        const val TAG = "LiveActivity"
    }
    //页面跳转传参的数据
    private val roomId  = "@TGS#aQ4OD4ASP"
    private val playerUrl = "http://3891.liveplay.myqcloud.com/live/3891_user_52df50b9_0c95.flv"
    private lateinit var mLivePlayer:V2TXLivePlayer //拉流组件
    private lateinit var mViewModel:LiveViewModel
    private lateinit var parser: SVGAParser
    private var webSocketUtils:WebSocketUtils? = null
    private val mBinding:ActivityLive2Binding by lazy {
        ActivityLive2Binding.inflate(layoutInflater)
    }

    private var giftEntity:GiftEntity? = null

    private val messageListener = MessageListener() //消息监听

    override fun initView() {
        super.initView()
        //模拟登录,主页面提前登录好了
        LiveIM.loginIM()
        Thread.sleep(1000)
        //加入群组：登录成功后才能加入群组
        V2TIMManager.getInstance().joinGroup(roomId,"",object : V2TIMCallback {
            override fun onSuccess() {
                Log.d(TAG, "加入成功: ")

            }

            override fun onError(p0: Int, p1: String?) {
                Log.d(TAG, "加入失败: $p0 $p1 ")
            }
        })
        //监听器接受消息
        V2TIMManager.getMessageManager().addAdvancedMsgListener(messageListener)
        //1:拉流
        mLivePlayer = V2TXLivePlayerImpl(this)
        mLivePlayer.setRenderView(mBinding.videoView)
        mLivePlayer.startLivePlay(playerUrl)
        //2:加入直播间
        lifecycleScope.launch {
            mViewModel.intents.send(LiveFansIntent.EnterRoom(roomId))
        }
        //3：礼物解析器
        parser = SVGAParser.shareParser() //解析器
        parser.init(this) //初始化

    }
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return mBinding.root
    }


    private fun initWebSocket(){
        webSocketUtils = WebSocketUtils.Builder()
            .setUri("ws://10.161.9.80:7037/liveRoom/websocket/$roomId/${UserMMKV.userId}")
            .setReceiveMessageListener(object : WebSocketUtils.ReceiveMessageListener{
                override fun onMessage(message: String?) {
                    if (message?.contains("heart") == false){
                        Log.d(TAG, "接收到消息: $message")
                        handleWebSocketMessage(message)
                    }
                }

                override fun onOpen(shake: ServerHandshake?) {
                    Log.d(TAG,"打开链接")

                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    Log.d(TAG, "断开链接: ")

                }

                override fun onError(ex: Exception?) {
                    Log.d(TAG, "链接错误:")

                }
            }).build()
    }

    /**
     * 处理websocket消息
     * 0：链接成功
     * 1：红包消息{"type":1,"data":{"id":565,"room_id":"10456123","count":1,"money":10.0,"time":60000,"createTime":"Oct 27, 2025, 4:06:16 PM","status":1}}
     * 3：中将名单{"type":3,"data":{"id":565,"room_id":"10456123","count":1,"money":10.0,"time":60000,"createTime":"Oct 27, 2025, 4:06:16 PM","users":"[]","win_users":"[]","status":1}}
        7:点赞热度 {"type":7,"data":20}
    8:礼物{"type":8,"data":"{\"gift\":{\"id\":1,\"name\":\"car\",\"title\":\"跑车\",\"imgUrl\":\"http://10.161.9.80:7015/gift/download/car\",\"price\":100,\"svgaPath\":\"\"},\"username\":\"ytx22\"}"}

    9:上车：{"type":9,"data":"586148"}
     10：下车 {"type":10,"data":"586148"}
     */
    private fun handleWebSocketMessage(message: String) {

        val jsonObject = JSONObject(message)
        val type = jsonObject.getInt("type")
        when(type){
            0 -> {
                showMsg("链接成功")
            }
            1 -> {
                showMsg("有新红包消息")
                showRedPacket(message)
            }
            3 ->{
                showMsg("中将名单")
                showWinders(message)
            }
            5 -> {
                showMsg("有人加入")
            }
            7 -> {
                showMsg("点赞热度")
            }
            8 -> {
                showMsg("礼物")
                giftEntity = Gson().fromJson(jsonObject.getJSONObject("data").getString("gift"), GiftEntity::class.java)
                showGiftSVGA()
            }
            9 -> {
                showMsg("上车") //更新recyclerview小黄车数据
            }
            10 -> {
                showMsg("下车") //更新recyclerview小黄车数据
            }
        }

    }

    private fun showWinders(message: String) {
        val jsonObject = JSONObject(message)
        val data = jsonObject.getJSONObject("data")
        val winUsers = data.getString("win_users")
        val arrary = winUsers.split(",")
        if (arrary.contains(UserMMKV.userId)) {
            showMsg("恭喜你中奖了")
        }else{
            showMsg("没有中将")
        }
    }

    private fun showRedPacket(message: String) {
        mBinding.ivRedPacket.visibility = View.VISIBLE

    }

    override fun initEvent() {
        super.initEvent()
        //点击红包--》参与抽奖
        mBinding.ivRedPacket.setSingClick {
            lifecycleScope.launch {
                mViewModel.intents.send(LiveFansIntent.JoinRedPacket(roomId))
            }
        }
        //小黄车
        mBinding.btGoodsList.setSingClick {
            lifecycleScope.launch {
                mViewModel.intents.send(LiveFansIntent.GoodsList(roomId))
            }
        }
        //点赞
        mBinding.bezierView.setCallBack(object : BezierView.CallBack{
            override fun onEnd() {
                lifecycleScope.launch {
                    mViewModel.intents.send(LiveFansIntent.AddHotLiveRoom(roomId))
                }
            }

        })
        //im发送消息
        mBinding.btSendMessage.setSingClick {
            LiveIM.sendMessage("这是我发送的消息",roomId)
        }
        /**
         * 发送礼物
         * 1：客户端判断当前金额是否充足
         * 2：访问接口，服务端扣除金额，返回结果
         * 3：成功展示礼物动画
         */
        mBinding.btGift.setSingClick {
           // 1：客户端判断当前金额是否充足：访问账号接口查看金币

            giftEntity = GiftEntity(
                id = 1,
                imgUrl = "http://10.161.9.80:7015/gift/download/car",
                name = "car",
                price = 100,
                svgaPath = "",
                title = "跑车"
            )
            lifecycleScope.launch {
                val entity = SendGiftRequestEntity(giftEntity = giftEntity!! , room_id = roomId)
                mViewModel.intents.send(LiveFansIntent.SendGift(entity))
            }


        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.enterRoomState_.collect{
                    when(it){
                        is EnterRoomState.Success -> {
                            showMsg("加入成功")
                            //3：订阅websocket消息
                            initWebSocket()
                        }
                        is EnterRoomState.Error -> {
                            showMsg("加入失败")

                        }
                        is EnterRoomState.Init -> {

                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.exitRoomState_.collect{
                    when(it){
                        is ExitRoomState.Success -> {
                            showMsg("退出成功")

                        }
                        is ExitRoomState.Error -> {
                            showMsg("退出失败")

                        }
                        is ExitRoomState.Init -> {

                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.joinRedPacketState_.collect{
                    when(it){
                        is JoinRedPacketState.Success -> {
                            showMsg("参与成功")
                            //弹出红包倒计时对话框

                        }
                        is JoinRedPacketState.Error -> {
                            showMsg("参与失败")

                        }
                        is JoinRedPacketState.Init -> {

                        }
                    }
                }
            }
        }
        //黄车
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.goodsListState_.collect{
                    when(it){
                        is GoodsListState.Success -> {
                            var str = ""
                            it.data.records.forEach { item ->
                                str+="${item.title}\n"
                            }
                            mBinding.tvGoods.text = str
                        }
                        is GoodsListState.Error -> {
                         mBinding.tvGoods.text = "失败"

                        }
                        is GoodsListState.Init -> {

                        }
                        is GoodsListState.Loading -> {
                            mBinding.tvGoods.text = "加载中"

                        }
                        is GoodsListState.Empty -> {
                            mBinding.tvGoods.text = "空空"
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.addHotLiveRoomState_.collect{
                    when(it){
                        is AddHotLiveRoomState.Success -> {
                            showMsg("点赞成功")

                        }
                        is AddHotLiveRoomState.Error -> {
                            showMsg("点赞失败")

                        }
                        is AddHotLiveRoomState.Init -> {}
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.sendGiftState_.collect{
                    when(it){
                        is SendGiftState.Success -> {
                            showMsg("发送成功")
                            //显示礼物动画
                            showGiftSVGA()
                        }
                        is SendGiftState.Error -> {
                            showMsg("发送失败")

                        }
                        is SendGiftState.Init -> {}
                    }
                }
            }
        }
    }

    private fun showGiftSVGA(){
        parser.decodeFromURL(URL(giftEntity?.imgUrl),object :SVGAParser.ParseCompletion{
            override fun onComplete(videoItem: SVGAVideoEntity) {
                Log.d(TAG, "onComplete: ")
                val svgaDrawable = SVGADrawable(videoItem)
                mBinding.svgaview.setImageDrawable(svgaDrawable)
                mBinding.svgaview.startAnimation()
            }

            override fun onError() {
                Log.d(TAG, "onError: ")
            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycleScope.launch {
            mViewModel.intents.send(LiveFansIntent.ExitRoom(roomId))
        }

        webSocketUtils?.closeConnect()
        //解除消息监听
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(messageListener)
    }

}